package com.shopAuth.service.impl;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shopAuth.bean.CheckAuth;
import com.shopAuth.dao.CheckAuthMapper;
import com.shopAuth.service.ICheckAuthService;

import shopBean.common.Exception.MyException;
import shopBean.common.bean.RestResult;
import shopBean.common.utils.DateCommonUtils;
import shopBean.common.utils.RestResultGenerator;
import shopBean.common.utils.Tool;

@Service("checkAuthService")
public class CheckAuthServiceImpl implements ICheckAuthService {
	@Autowired
	CheckAuthMapper checkAuthMapper;
	@Value("${spring.profiles.active}")
	String systemRun;
	private static Logger logger = LoggerFactory.getLogger(CheckAuthServiceImpl.class);
	@Transactional
	public RestResult sendCode(String tel) throws MyException {
		CheckAuth checkAuth = new CheckAuth();
		checkAuth.setTel(tel);
		checkAuth.setCheckCode(Tool.createTelCode()+"");
		checkAuth.setCreateDate(DateCommonUtils.getCurrent());
		checkAuth.setUse(0);
		checkAuthMapper.insert(checkAuth);
		logger.info("环境"+systemRun);
		if(systemRun.equals("dev")){
			return RestResultGenerator.genSuccessResult(checkAuth.getCheckCode());
		}
		return RestResultGenerator.genSuccessResult();
	}
	public boolean checkCode(String tel,String code,boolean flag) throws MyException {
		CheckAuth checkAuth = new CheckAuth();
		checkAuth.setTel(tel);
		CheckAuth result = checkAuthMapper.getFrist(checkAuth);
		if(result == null){
			return false;
		}
		if(result.getUse()==1 ||DateCommonUtils.currentDateSubtractDate(result.getCreateDate())>5*60*1000){
			return false;
		}
		if(!result.getCheckCode().equals(code)){
			return false;
		}
		if(flag) {
			result.setUse(1);
			checkAuthMapper.update(result);	
		}
		
		return true;
	}
}
